package com.kfyty.auto.host.api;

import com.kfyty.loveqq.framework.core.autoconfig.InitializingBean;
import com.kfyty.loveqq.framework.core.autoconfig.annotation.Component;
import com.kfyty.loveqq.framework.core.exception.ResolvableException;
import com.kfyty.loveqq.framework.core.support.json.JSON;
import com.kfyty.loveqq.framework.core.utils.JsonUtil;
import com.kfyty.loveqq.framework.sdk.api.core.config.ApiConfiguration;
import com.kfyty.loveqq.framework.sdk.api.core.reactive.http.ReactiveApis;
import com.kfyty.loveqq.framework.sdk.api.core.reactive.http.executor.ReactiveHttpClientHttpRequestExecutor;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class IP138HostSearchApi implements HostSearchApi, InitializingBean {

    @Override
    public void afterPropertiesSet() {
        ApiConfiguration.getGlobalConfiguration().setRequestExecutor(new ReactiveHttpClientHttpRequestExecutor());
    }

    @Override
    public List<String> search(String host) {
        byte[] executed = new ReactiveApis()
                .requestPath("https://site.ip138.com/domain/read.do?domain=github.com&time=1761278080163")
                .method("GET")
                .addQuery("domain", host)
                .addQuery("time", String.valueOf(System.currentTimeMillis()))
                .addHeader("Host", "site.ip138.com")
                .addHeader("referer", "https://site.ip138.com/github.com/")
                .addHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36")
                .addHeader("cookie", "BAIDU_SSP_lcr=https://cn.bing.com/; Hm_lvt_87bc7ddd9343f0d90c7b3783bf28097f=1761277959; HMACCOUNT=E7A772FC97299138; Hm_lpvt_87bc7ddd9343f0d90c7b3783bf28097f=" + (System.currentTimeMillis() / 1000))
                .execute();
        JSON json = JsonUtil.toJSON(new String(executed));
        if (json.getInteger("code") == 300 && json.getBoolean("status")) {
            return json.getArray("data")
                    .stream()
                    .map(e -> json.getJSON(e, "not json"))
                    .map(e -> e.getString("ip"))
                    .filter(e -> !e.equals("127.0.0.1"))
                    .collect(Collectors.toList());
        }
        throw new ResolvableException(json.toString());
    }
}
